package com.lpf;

import com.google.common.util.concurrent.RateLimiter;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class RateLimiterMain {

    RateLimiter rateLimiter = RateLimiter.create(10);

    public void doTests() {
        if (rateLimiter.tryAcquire()) { // 这里就是获取一个令牌
            System.out.println("允许通过进行访问");
        } else {
            System.out.println("被限流了");
        }
    }

    public static void main(String[] args) throws IOException {
        RateLimiterMain rateLimiterMain = new RateLimiterMain();
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                    Thread.sleep(random.nextInt(1000));
                    rateLimiterMain.doTests();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        countDownLatch.countDown();
        System.in.read();
    }
}
